﻿namespace YidanSoft.Library.EditorUtility.Win32
{
    using Microsoft.Win32;
    using System;

    public class RegistryUtil
    {
        private RegistryUtil()
        {
        }

        public static string ReadFromRegistry(RegistryKey RegHive, string RegPath, string KeyName, string DefaultValue)
        {
            string str = "";
            string[] strArray = RegPath.Split(new char[] { '\\' });
            RegistryKey[] keyArray = new RegistryKey[strArray.Length + 1];
            keyArray[0] = RegHive;
            for (int i = 0; i < strArray.Length; i++)
            {
                keyArray[i + 1] = keyArray[i].OpenSubKey(strArray[i]);
                if (i == (strArray.Length - 1))
                {
                    str = (string) keyArray[i + 1].GetValue(KeyName, DefaultValue);
                }
            }
            return str;
        }

        public static void WriteToRegistry(RegistryKey RegHive, string RegPath, string KeyName, string KeyValue)
        {
            string[] strArray = RegPath.Split(new char[] { '\\' });
            RegistryKey[] keyArray = new RegistryKey[strArray.Length + 1];
            keyArray[0] = RegHive;
            for (int i = 0; i < strArray.Length; i++)
            {
                keyArray[i + 1] = keyArray[i].OpenSubKey(strArray[i], true);
                if (keyArray[i + 1] == null)
                {
                    keyArray[i + 1] = keyArray[i].CreateSubKey(strArray[i]);
                }
            }
            try
            {
                keyArray[strArray.Length].SetValue(KeyName, KeyValue);
            }
            catch (NullReferenceException)
            {
                throw new Exception("Null Reference");
            }
            catch (UnauthorizedAccessException)
            {
                throw new Exception("Unauthorized Access");
            }
        }
    }
}

